﻿using Api.Application.Command.User;
using Api.DTO;
using Common.Architecture.Common;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace Api.Application.Handler.User
{
    public class LoginUserHandler : IRequestHandler<LoginUserCommand, ApiResult<LoginDTO>>
    {
        private readonly IBase<UserModel> userRepo;
        private readonly IBase<RoleModel> roleRepo;
        private readonly IBase<UserRoleModel> userRoleRepo;
        private readonly IBase<DeionModel> deionRepo;
        private readonly JwtTools jwtTools;
        private readonly IConfiguration configuration;

        public LoginUserHandler(IBase<UserModel>userRepo,IBase<RoleModel>roleRepo,IBase<UserRoleModel> userRoleRepo,IBase<DeionModel> deionRepo,JwtTools jwtTools,IConfiguration configuration)
        {
            this.userRepo = userRepo;
            this.roleRepo = roleRepo;
            this.userRoleRepo = userRoleRepo;
            this.deionRepo = deionRepo;
            this.jwtTools = jwtTools;
            this.configuration = configuration;
        }
        public Task<ApiResult<LoginDTO>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<LoginDTO> result= new ApiResult<LoginDTO>();
            var user = userRepo.GetAll().Where(x => x.UserName == request.UserName).FirstOrDefault();
            var deion = deionRepo.GetAll();
            if (user==null)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "账号不存在";
                return Task.FromResult(result);
            }
            if (user.Pwd != request.Pwd)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "密码错误";
                return Task.FromResult(result);
            }
            var userId=user.Id;
            var userrole = userRoleRepo.GetAll().Where(x => x.UserId == userId).FirstOrDefault();
            var role=roleRepo.GetValue(userrole.RoleId).Result;
            LoginDTO loginDTO = new LoginDTO()
            {
                UserId = userId,
                UserName = request.UserName,
                RoleId = role.Id,
                RoleName=role.RoleName,
                DeionId=user.DeionId,
                token = jwtTools.JwrNewString(configuration, user.Id.ToString())
            };
            if (user != null)
            {
                
                result.Code = ApiEnum.OK;
                result.Data = loginDTO;
                
                result.Msg = "登录成功";
            }
            else
            {
                result.Code = ApiEnum.Fail;

            }
            //result.Code = ApiEnum.OK;
            //result.Data = loginDTO;
            //result.Msg = "登录成功";
            return Task.FromResult(result);
        }
    }
}
